package DAO.gerenciador;

import java.util.List;

import org.droidpersistence.dao.DroidDao;
import org.droidpersistence.dao.TableDefinition;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.os.SystemClock;

/*
 * Esta classe serve como template de C.R.U.D. generico.
 * obs: Para compor esta classe a entidade deve estar mapeada com droidPersistence
 */

class DroidPersistenceGenerico<T> {

	private DroidDao dao;
	private SQLiteDatabase database;
	
	public DroidPersistenceGenerico(Context context,DroidDao<T, Long> dao, TableDefinition<T> def,SQLiteDatabase database) {
		
		setDatabase(database);
		this.dao = dao;
	}
	
	private void openDb(){
		if(! getDatabase().isOpen()){
			setDatabase(SQLiteDatabase.openDatabase(Environment.getDataDirectory() + "/db/kaeDB.db", null, SQLiteDatabase.OPEN_READWRITE));
		}
	}
	
	private void closeDb() {
		if (getDatabase().isOpen()) {
			getDatabase().close();
	    }
	}
	
	public SQLiteDatabase getDatabase() {
		return database;
	}
	public void setDatabase(SQLiteDatabase database) {
		this.database = database;
	}

	private void resetDb() {      
		closeDb();
	    SystemClock.sleep(500);
	    openDb();
	}
	
	public void salvar(T modelo){
		try {
			getDatabase().beginTransaction();
			dao.save(modelo);
			getDatabase().setTransactionSuccessful();
		} catch (Exception e) {
			System.err.println("Erro ao salvar no banco de dados ERR: " + e.getMessage());
		}		
		getDatabase().endTransaction();
	}
	
	public T pesquisar(Long id){
		T resultado = (T) dao.get(id);
		return resultado;
	}
	
	public List<T> pesquisarTodos() {
		List<T> resultado = dao.getAll();
		return resultado;
	}
	
	public boolean deletar(Long id){
		
		boolean result = false;
		getDatabase().beginTransaction();
		result = dao.delete(id);
		getDatabase().setTransactionSuccessful();
		getDatabase().endTransaction();
		return result;
	}
	
	public boolean atualizar(T modelo, Long id){
		boolean result = false;
		try {
		getDatabase().beginTransaction();
		dao.update(modelo, id);
		getDatabase().setTransactionSuccessful();
		result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}		
		getDatabase().endTransaction();
		return result;
	}
	
}
